﻿(function($){
	$.extend({Web:{
		host:'',
		empId:'',
		websocket:null,
		Handlers:[],//注册的事件
		init:function(host, empId){//初始化连接
			if (this.websocket != null) {
				//销毁当前的websocket对象
				try{this.websocket.close()}catch(e){console.log(e);}
			}
			this.host = host;
			this.empId = empId;
			if (!('WebSocket' in window)) {
				 alert("您的浏览器不支持websocket！将无法使用站内信以及各种实时通知类功能！请下载谷歌浏览器，尽量避免使用IE！");
				 return;
			}
			
			var protol = window.location.href.startsWith("https://")?"wss://":"ws://";
			this.websocket= new WebSocket(protol+host+"/websocket/"+empId);
			
			// 收到服务端消息
			this.websocket.onmessage = function (msg) {
			 	$.Web.trigger("onmessage", JSON.parse(msg.data));
			};
			
			// 异常
			this.websocket.onerror = function (msg) {
				$.Web.trigger("onerror", msg);
			};
			
			// 建立连接
			this.websocket.onopen = function (event) {
				$.Web.trigger("onopen", event);
			};
			
			// 断线重连
			this.websocket.onclose = function () {
				console.log("websocket关闭事件触发！");
				$.Web.trigger("onclose",{});
				// 重试10次，每次之间间隔10秒
				setTimeout(function () {
					$.Web.init($.Web.host, $.Web.empId);
				}, 1000);
			};
		},
		close : function() {
			// 关闭连接
			if ($.Web.websocket == null) {
				console.log('未连接');
				return;
			}
			$.Web.websocket.close();
		},
		send:function(options){
			if ($.Web.websocket == null) {
				console.error('未连接');
				return;
			}
			options.empId=$.Web.empId;
			var msg=JSON.stringify(options)
			$.Web.websocket.send(msg);
		},
		on:function (eventName, handler) {
			//注册事件
			var bFind = false;        
			for (var index = 0; index < $.Web.Handlers.length; index++) {
				if ($.Web.Handlers[index].handler == handler) {
					bFind = true;
					break;
				}
			}
	        if(bFind == false) {
	        	$.Web.Handlers.push({ name: eventName, handler: handler });
	        } else {
	        	console.info('事件处理函数 ' + handler + ' (' + eventName + ') 被重复注册');
	        }
		},
		un:function(eventName,handler) {
			//注销事件
	        var itemindex = -1;
	        for (var index = 0; index < $.Web.Handlers.length; index++) {
	            if ($.Web.Handlers[index].name == eventName && $.Web.Handlers[index].handler == handler) {
	                itemindex = index;
	                break;
	            }
	        }
	        if (itemindex > -1) {
	        	$.Web.Handlers.splice(itemindex, 1);
	        }
		},
		trigger:function(fnName,param) {
			//触发事件 
			for (var index = 0; index < $.Web.Handlers.length; index++) {
	            if ($.Web.Handlers[index].name == fnName) {
	                setTimeout($.Web.Handlers[index].handler(param),0);
	            }
	        }
		}
	}});
})(jQuery);